/**
 * 微信公众号登录
 * @author 许明浩 微信: muaiyuese
 */
import { useState, useEffect } from "react";
import { View, Text, Image } from "@tarojs/components";
import { navigateTo, switchTab, navigateBack } from "@tarojs/taro";
import { getSearchParams } from "@/lib/get-search-params";
import { SafeArea, Button } from "@nutui/nutui-react-taro";
import { instance as Log } from "@/lib/log";
import { authSnsapiUserinfo } from "@/lib/auth/wechat";
import { delQueStr, paramsToQuery } from "@/lib";
import { ApiWxLogin } from "@/api/auth";
import { getUserInfo } from "@/lib/auth";
import Layout from "@/components/layout";

function Wechat() {
  // const [checkedAgreement, setCheckedAgreement] = useState([]);
  const [loading, setLoading] = useState(false);

  /**
   * 网页授权-非静默
   * @param {}
   * @return
   */
  const handleWechatAuth = () => {
    // if (!checkedAgreement?.length) {
    //   Taro.showToast({
    //     title: "请同意用户协议",
    //     icon: "none",
    //     duration: 2000,
    //   });
    //   return;
    // }
    const _params: any = {};
    if (getSearchParams("backurl") || getSearchParams("isSwitchTab")) {
      _params.backurl = getSearchParams("backurl");
      _params.isSwitchTab = getSearchParams("isSwitchTab");
    }
    authSnsapiUserinfo({
      redirect_uri: encodeURIComponent(
        `${
          window.location.origin
        }/#/sub_common/pages/auth/wechat/index${paramsToQuery(_params)}`
      ),
    });
  };

  useEffect(() => {
    const code = getSearchParams("code");
    delQueStr(window.location.href, "code");
    delQueStr(window.location.href, "state");
    if (code) {
      checkCode(code);
    }
  }, []);

  /**
   * 根据code判断逻辑
   * hasRelation: false
   * @param {}
   * @return
   */
  const checkCode = (code) => {
    setLoading(true);
    ApiWxLogin({ code, appId: process.env.WECHAT_APPID })
      .then((res) => {
        const {
          hasRelation,
          token,
          exipreTime = Date.now() + 3600 * 24 * 7,
        } = res?.data || {};
        if (hasRelation) {
          if (!token) {
            Log.error("绑定过账户，但是后端未返回token", res);
            return;
          }
          Log.log("公众号网页授权数据", res);
          getUserInfo({
            token,
            exipreTime,
            callback: () => {
              const backurl = decodeURIComponent(
                decodeURIComponent(getSearchParams("backurl"))
              );
              const isSwitchTab = getSearchParams("isSwitchTab");
              if (backurl) {
                const _history = isSwitchTab ? switchTab : navigateTo;
                _history({
                  url: backurl,
                });
              } else {
                navigateBack({
                  delta: 1,
                });
              }
            },
          });
        } else {
          const backurl = getSearchParams("backurl");
          const isSwitchTab = getSearchParams("isSwitchTab");
          navigateTo({
            url:
              "/sub_common/pages/auth/login/index" +
              `?backurl=${backurl}&isSwitchTab=${isSwitchTab}`,
          });
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };
  return (
    <Layout noheader nofooter disableDict loading={loading}>
      <SafeArea position="top"></SafeArea>
      <View className="flex items-center justify-center my-[180rpx]">
        <Image
          src={require("@/assets/img/logo/icon-192x192.png")}
          className="w-[100rpx] h-[100rpx]"
        />
        <View className="ml-1 flex flex-col">
          <Text className="text-[36rpx] leading-none font-medium">
            <Text className="text-[#446ea3]">云上</Text>
            <Text className="text-[#bd6f3e]">之枫</Text>
          </Text>
          <Text className="text-[24rpx] text-[#aaa] leading-none mt-1">
            网络工作室
          </Text>
        </View>
      </View>
      <View className="mt-0 mx-[50rpx]">
        <View className="h-[96rpx] relative">
          <Button block type="success" size="large" onClick={handleWechatAuth}>
            微信用户一键登录
          </Button>
        </View>
      </View>
      <View className="mt-6 mx-[50rpx] mb-[28rpx]">
        <View className="h-[96rpx] relative">
          <Button
            block
            size="large"
            onClick={() => {
              const backurl = getSearchParams("backurl");
              const isSwitchTab = getSearchParams("isSwitchTab");
              navigateTo({
                url:
                  "/sub_common/pages/auth/login/index" +
                  `?backurl=${backurl}&isSwitchTab=${isSwitchTab}`,
              });
            }}
          >
            手机号登录
          </Button>
        </View>
      </View>
    </Layout>
  );
}

export default Wechat;
